package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.repository.StrategyTemplateRepository;
import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.service.IStrategySearchService;
import cn.wolfcode.luowowo.search.template.StrategyTemplate;
import cn.wolfcode.luowowo.search.vo.StatsResult;
import org.apache.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.bucket.composite.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import java.util.*;

@Service
public class StrategySearchServiceImpl implements IStrategySearchService {
    @Autowired
    private StrategyTemplateRepository repository;

    @Override
    public void save(StrategyTemplate template) {
        repository.save(template);
    }

    @Override
    public List<StatsResult> listCondition(int condition) {
        String id = null;
        String name = null;
        switch (condition){
            case SearchQueryObject.CONDITION_UNABROAD:
                id = "provinceId";
                name = "provinceName";
                break;
            case SearchQueryObject.CONDITION_ABROAD:
                id = "countryId";
                name = "countryName";
                break;
            case SearchQueryObject.CONDITION_THEME:
                id = "themeId";
                name = "themeName";
                break;
        }
        return groupSearch(id,name);
    }


    private List<StatsResult> groupSearch(String id, String name) {
        String conditionField = "condition";
        String idField = "id";
        String nameField = "name";

        List<StatsResult> list = new ArrayList<>();

        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();

        //构建桶聚合字段
        List<CompositeValuesSourceBuilder<?>> sources = new ArrayList<>();
        sources.add(new TermsValuesSourceBuilder(idField).field(id));
        sources.add(new TermsValuesSourceBuilder(nameField).field(name));

        //构建aggs
        CompositeAggregationBuilder aggs = new CompositeAggregationBuilder(conditionField, sources);

        //设置pageSize = 1
        builder.withPageable(PageRequest.of(0, 1));

        builder.addAggregation(aggs); //添加aggs

        //如果查询国内数据则保证countryId=1
        if (id.equals("provinceId")) {
            builder.withQuery(QueryBuilders.termQuery("countryId", "1"));
        }

        //执行查询
        AggregatedPage<StrategyTemplate> page = (AggregatedPage<StrategyTemplate>) repository.search(builder.build());
        //拿到桶聚合的结果
        InternalComposite agg = (InternalComposite) page.getAggregation(conditionField);
        //获取每一个桶对象
        for (CompositeAggregation.Bucket bucket : agg.getBuckets()) {
            Map<String, Object> key = bucket.getKey();
            /* 从桶中拿到我们要的id,name,doc_count数据,封装成StatsResult对象
                {
                    key : {id: xx, name: xxx},
                    doc_count : xx
                }
             */
            Object idX = key.get(idField);
            Object nameX = key.get(nameField);

            StatsResult vo = new StatsResult(Long.parseLong(idX.toString()), nameX.toString(),
                    bucket.getDocCount());
            list.add(vo);
        }
        return list;

    }

    @Override
    public Object query(SearchQueryObject qo) {
        Page<StrategyTemplate> page = null;
        switch (qo.getType()){
            case SearchQueryObject.CONDITION_UNABROAD :
                //国内,根据省份id查询
                page = repository.findByProvinceId(qo.getTypeValue(),qo.getPageable());
                break;
            case SearchQueryObject.CONDITION_ABROAD:
                //国外,根据国家id查询
                page = repository.findByCountryId(qo.getTypeValue(),qo.getPageable());
                break;
            case SearchQueryObject.CONDITION_THEME:
                //主题.根据主题id查询
                page = repository.findByThemeId(qo.getTypeValue(),qo.getPageable());
                break;
                default:
                    page = repository.findAll(qo.getPageable());
        }
        return page;
    }

    @Override
    public List<Map<String, Object>> listThemeTop10() {
        List<Map<String,Object>> list = new ArrayList<>();
        //查询所有主题统聚合结果
        List<StatsResult> vos = groupSearch("themeId", "themeName");
        //排序
        Collections.sort(vos,(o1,o2)->{
            Long val = o1.getCount() - o2.getCount();
            return val.intValue();
        });
        //截取10个
        if (vos.size() > 10){
            vos.subList(0,10);
        }
        for (StatsResult vo : vos) {
            Map<String,Object> map = new HashMap<>();
            map.put("theme",vo);
            //根据主题id查询攻略挂载的目的地
            Page<StrategyTemplate> sts = repository.findByThemeId(vo.getId(), null);
            //将所有目的地存入set,使用set,可以去重,因为文章下的目的地可能重复
            Set<StatsResult> set = new HashSet<>();
            for (StrategyTemplate st : sts) {
                //设置目的地id,目的地名称
                //StatsResult底层重写了hascode和equals方法
                set.add(new StatsResult(st.getDestId(),st.getDestName(),null));
            }
            map.put("dests",set);
            list.add(map);
        }
        return list;
    }

    @Override
    public List<StrategyTemplate> listByDestName(String keyword) {
        return repository.findByDestName(keyword);
    }
}
